# -*- coding: utf-8 -*- 
# @Time : 2023/6/5 18:03 
# @Author : gkm
# @File : project.py

from django import forms
from django.core.exceptions import ValidationError
from web.forms.bootstrap import BootStrapForm
from web import models
from web.forms.widgets import ColorRadioSelect


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    '''创建项目表单'''
    bootstrap_class_exclude = ['color']

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        '''项目校验'''
        name = self.cleaned_data['name']
        # 1. 判断当前项目是否已创建
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目已存在')
        # 2. 当前用户是否有额度创建项目
        # 现在已创建的项目个数
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        # 与最多创建的项目个数比较

        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请购买套餐')

        return name
